
package at.htlkaindorf.jee.jasper.jasperreportsexample1;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

/**
 *
 * @author Thomas
 */
public class InvoiceReportGenerator {

    private static final String reportTemplateResourcePath = "invoice.jasper";

    public static void main(final String[] args) throws JRException {
        final Locale locale = Locale.GERMAN;
        final String clientName = "Mustermann";
        final JasperPrint reportPrint = JasperFillManager.fillReport(fetchInvoiceReportTemplate(), applyParameters(locale, clientName), createDataSource());
        JasperExportManager.exportReportToPdfFile(reportPrint, "src/main/resources/pdf/Invoice.pdf");
    }
    
    private static InputStream fetchInvoiceReportTemplate(){
        InputStream reportTemplate = ClassLoader.getSystemClassLoader().getResourceAsStream(reportTemplateResourcePath);
        if (reportTemplate == null) {
            throw new IllegalArgumentException("could not find report template");
        }
        return reportTemplate;
    }

    private static Map<String, Object> applyParameters(Locale locale, String clientName) {
        final Map<String, Object> params = new HashMap<>();
        params.put("client_name", clientName);
        params.put(JRParameter.REPORT_LOCALE, locale);
        return params;
    }

    private static JRBeanCollectionDataSource createDataSource() {
        final List<InvoiceLine> invoiceLines = new LinkedList<>();

        final InvoiceLine waterInvoiceLine = new InvoiceLine();
        waterInvoiceLine.setDesignation("Wasser");
        waterInvoiceLine.setAmount(2);
        waterInvoiceLine.setUnitDesignation("Liter");
        waterInvoiceLine.setPrice(new BigDecimal(10));

        final InvoiceLine potatoInvoiceLine = new InvoiceLine();
        potatoInvoiceLine.setDesignation("Kartoffeln");
        potatoInvoiceLine.setAmount(2);
        potatoInvoiceLine.setUnitDesignation("kg");
        potatoInvoiceLine.setPrice(new BigDecimal("10.2"));

        final InvoiceLine airInvoiceLine = new InvoiceLine();
        airInvoiceLine.setDesignation("Luft");
        airInvoiceLine.setAmount(5);
        airInvoiceLine.setUnitDesignation("m³");
        airInvoiceLine.setPrice(new BigDecimal("10.4999"));

        invoiceLines.add(waterInvoiceLine);
        invoiceLines.add(potatoInvoiceLine);
        invoiceLines.add(airInvoiceLine);

        return new JRBeanCollectionDataSource(invoiceLines);
    }

}
